<?php
namespace Dao;

class Rules extends DbTable {
	/**
	 * 初始状态。
	 * @var int
	 */
	const STATUS_INIT = 1;
	/**
	 * 等待提交预订。
	 * @var int
	 */
	const STATUS_LOCK = 2;
	/**
	 * 已成功预订。
	 * @var int
	 */
	const STATUS_SUCC = 3;
	
	/**
	 * 表字段定义。
	 * @var array
	 */
	protected $_numeric = ['rid', 'status', 'early', 'latest'];

	/**
	 * 添加一条预订规则。
	 *
	 * @param string $from
	 * @param string $to
	 * @param string $dater
	 * @param int $early
	 * @param int $latest
	 * @param array $seat
	 * @param array $passenger
	 * @return boolean
	 */
	public function addRule($from, $to, $dater, $early, $latest, $seat, $passenger) {
		$from = trim($from);
		$to = trim($to);
		$dater = trim($dater);
		$early = intval($early);
		$latest = intval($latest);
		
		if (!$from || !$to || !preg_match('/^\d+\-\d+\-\d+$/', $dater) || $early <= time() || $latest <= time() || !$seat || !$passenger) {
			return FALSE;
		}
		
		$seat = json_encode($seat, JSON_UNESCAPED_UNICODE);
		$passenger = json_encode($passenger, JSON_UNESCAPED_UNICODE);
		
		return $this->insert(array('from' => $from, 'to' => $to, 'dater' => $dater, 'early' => $early, 'latest' => $latest, 'seat' => $seat, 'passenger' => $passenger));
	}

	/**
	 * 设置规则是否已经预订。
	 *
	 * @param int $rid
	 * @param int $src
	 * @param int $status
	 * @reutrn boolean
	 */
	public function toStatus($rid, $src, $status = NULL) {
		if (!in_array($src, [self::STATUS_INIT, self::STATUS_LOCK, self::STATUS_SUCC])) {
			return FALSE;
		} elseif ($status && !in_array($status, [self::STATUS_INIT, self::STATUS_LOCK, self::STATUS_SUCC])) {
			return FALSE;
		}
		
		$where['rid'] = $rid;
		$status && $where['status'] = $status;
		
		return $this->update(array('status' => $src), $where);
	}

	/**
	 * 获得所有规则。
	 *
	 * @reutrn array
	 */
	public function getAll() {
		$list = $this->select();
		
		$rules = [];
		
		foreach ($list as $rid => $item) {
			$rules[$rid] = $item;
			$rules[$rid]['seat'] = json_decode($item['seat'], TRUE);
			$rules[$rid]['passenger'] = json_decode($item['passenger'], TRUE);
		}
		
		return $rules;
	}

	/**
	 * 获得指定上下车站和日期且未被预订的所有规则。
	 *
	 * @param string $from
	 * @param string $to
	 * @param string $dater
	 * @reutrn array
	 */
	public function getRule($from, $to, $dater) {
		$rules = $this->select(array('status' => self::STATUS_INIT, 'from' => $from, 'to' => $to, 'dater' => $dater))->fetch();
		
		foreach ($rules as &$item) {
			$item['seat'] = json_decode($item['seat'], TRUE);
			$item['passenger'] = json_decode($item['passenger'], TRUE);
		}
		
		return $rules;
	}
}